package com.heima.article.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.heima.article.mapper.ArticleMapper;
import com.heima.article.service.ArticleFreemarkerService;
import com.heima.common.constants.ArticleConstants;
import com.heima.file.service.FileStorageService;
import com.heima.model.article.pojos.ApArticle;
import com.heima.model.search.vos.SearchArticleVo;
import freemarker.template.Configuration;
import freemarker.template.Template;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.ByteArrayInputStream;
import java.io.StringWriter;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;


/**
 * @author Xiao
 * @version 1.0
 * @description
 * @date 2021/11/24
 */
@Service
@Transactional
public class ArticleFreemarkerServiceImpl implements ArticleFreemarkerService {
    @Autowired
    private Configuration configuration;
    @Autowired
    private FileStorageService fileStorageService;
    @Autowired
    private ArticleMapper articleMapper;

    /**
     * 生成静态文件上传到minIO中
     * @param apArticle
     * @param content
     */
    @Override
    @Async
    public void buildArticleToMinIO(ApArticle apArticle, String content) {
        String staticUrl = apArticle.getStaticUrl();
        //删除旧的模板
        if (StringUtils.isNotBlank(staticUrl)) {
            fileStorageService.delete(staticUrl);
        }
        try {
            //文章内容通过freemarker生成html文件
            //获取模板
            StringWriter stringWriter = new StringWriter();
            Template template = configuration.getTemplate(ArticleConstants.TEMPLATE_NAME);
            //构造数据模型
            Map<String, Object> params = new HashMap<>();
            params.put(ArticleConstants.PARAM_KEY_CONTENT, JSONArray.parseArray(content));
            template.process(params, stringWriter);
            //合成html文件
            ByteArrayInputStream inputStream = new ByteArrayInputStream(
                    stringWriter.toString().getBytes(StandardCharsets.UTF_8));
            //把html文件上传到minio中
            staticUrl = fileStorageService.uploadHtmlFile(
                    null,
                    apArticle.getId() + ArticleConstants.FILE_SUFFIX_HTML,
                    inputStream);
            //修改ap_article表，保存static_url字段
            apArticle.setStaticUrl(staticUrl);
            articleMapper.updateById(apArticle);
            //发送消息，创建索引
            createArticleESIndex(apArticle, content, staticUrl);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Autowired
    private KafkaTemplate<String,String> kafkaTemplate;

    /**
     * 发送消息，创建索引
     * @param apArticle
     * @param content
     * @param staticUrl
     */
    private void createArticleESIndex(ApArticle apArticle, String content, String staticUrl) {
        SearchArticleVo vo = new SearchArticleVo();
        BeanUtils.copyProperties(apArticle,vo);
        vo.setContent(content);
        vo.setStaticUrl(staticUrl);
        kafkaTemplate.send(ArticleConstants.ARTICLE_ES_SYNC_TOPIC, JSON.toJSONString(vo));
    }
}
